// #include "util.hpp"
// #include "level.hpp"
// #include "message.hpp"
// #include "format.hpp"
// #include "sink.hpp"
// #include "logger.hpp"
// #include "buffer.hpp"
#include "../logs/log.h"

// 都转换成相应的秒数
enum TimeType
{
    SECOND,
    MINUTE,
    HOUR,
    DAY
};

class TimeSink : public log::Sink
{
public:
    TimeSink(std::string basename, TimeType gapSize) : _basename(basename)
    {
        switch (gapSize)
        {
        case SECOND:
            _gapSize = 1;
            break;
        case MINUTE:
            _gapSize = 60;
            break;
        case HOUR:
            _gapSize = 3600;
            break;
        case DAY:
            _gapSize = 3600 * 24;
            break;
        }
        std::string filename = createNewFile();
        _curGap = _gapSize == 1 ? log::Date::curTime() : log::Date::curTime() / _gapSize; // 当前是第几个时间段
        log::File::createDir(log::File::getPath(filename));
        _ofs.open(filename, std::ios::binary | std::ios::app);
        assert(_ofs.is_open());
    }

    void logOut(const char *data, int len)
    {
        if (log::Date::curTime() / _gapSize != _curGap)
        {
            _ofs.close();
            std::string filename = createNewFile();
            _ofs.open(filename, std::ios::binary | std::ios::app);
            assert(_ofs.is_open());
        }
        _ofs.write(data, len);
        assert(_ofs.good());
    }

private:
    std::string createNewFile()
    {
        time_t tt = log::Date::curTime();
        struct tm t;
        localtime_r(&tt, &t);
        std::stringstream ss;
        ss << _basename << t.tm_year + 1900 << t.tm_mon + 1 << t.tm_mday << t.tm_hour << t.tm_min << t.tm_sec << ".log";
        return ss.str();
    }

private:
    std::string _basename;
    std::ofstream _ofs;
    int _curGap;  // 当前所处的时间段
    int _gapSize; // 时间段的大小
};

int main()
{
    //log::Sink::ptr time_lsp = log::SinkFactory::create<TimeSink>("./time/time-", SECOND);
    std::unique_ptr<log::LoggerBuilder> builder(new log::GlobalLoggerBuiler());
    builder->BuilderType(log::ASYNC_LOGGER);
    builder->BuilderName("async_logger");
    builder->BuilderLevel(log::DEBUG);
    builder->BuilderEnableUnsafeAsync();
    builder->BuilderFormat("[%c]%m%n");
    builder->BuilderSink<TimeSink>("./time/time-", SECOND);
    log::Logger::ptr logger = builder->Build();

    time_t oldTime = log::Date::curTime();
    int count = 0;
    while(log::Date::curTime() < oldTime + 5)
    {
        logger->DEBUG("测试-%d", ++count);
    }
    return 0;
}